import axios from 'axios';

let loadDialog, requestNum = 0;

//获取get参数值
export function getUrlKey(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null;
}

//项目网络请求
export function baseRequest(param) {
    //添加全局网络请求状态
    if (param.vueObj) param.vueObj.$root.loading = true;
    //默认请求时添加加载框
    if (param.showLoading == undefined) param.showLoading = true;
    return new Promise((resolve, reject) => {
        const realUrl = param.url;
        let token = localStorage.getItem('token') ? localStorage.getItem('token') : '';
        if (param.showLoading)
            startNetWork("加载中");
        let axiosObj = param.method === "post" ? axios.post(realUrl,param.data, {
            headers: {
                'Authorization': 'Bearer ' + token,
                'X-TrackingId': getUuid(32, 16)
            }
        }) : param.method === "postJson" ? axios.post(realUrl, param.data, {
            headers: {
                'Authorization': 'Bearer ' + token,
                'X-TrackingId': getUuid(32, 16)
            }
        }) : axios.get(realUrl, {
            params: param.data,
            headers: {
                'Authorization': 'Bearer ' + token,
                'X-TrackingId': getUuid(32, 16)
            }
        });
        requestNum++;
        axiosObj.then((response) => {
            requestNum--;
            if (requestNum == 0)
                stopNetWork();
            if (param.vueObj)
                param.vueObj.$root.loading = false;
            try {
                if (response.data.responseCode != 0) {
                    toast(response.data.responseMessage)
                }
                response.data.data = JSON.parse(strencode(response.data.data));
                console.log(response.data.data, param.url);
                resolve(response.data.data);
            } catch (e) {
                console.log(e);
                toast("网络错误，请重试");
            }
        }).catch((response) => {
            requestNum--;
            if (requestNum == 0)
                stopNetWork();
            console.log(response.response, '失败返回');
            try {
                if (response.response.data.responseCode == -5) {
                    sessionStorage.clear();
                    localStorage.clear();
                    param.vueObj.$router.replace('/login');
                    return;
                }
                if (response.response.status === 404) {
                    setShade('后台服务404');
                    return;
                }
                if (param.showType === 'shade') {
                    setShade(response.response.data.responseMessage);
                    return;
                }
                toast(response.response.data.responseMessage)

            } catch (e) {
                if (param.showType === 'shade') {
                    setShade('网络错误，请重试');
                    return;
                }
                toast('网络错误，请重试')
            }
            if (!param.isCommon) {
                reject(response);
                return;
            }
        });
    })
}

//获取系统语言
export function getLanguage() {
    let lang = 'zh';
    let localStorageLang = localStorage.getItem('lang');
    if (localStorageLang != null && localStorageLang != '') {
        return localStorageLang;
    }
    if (getUrlKey('lang') == null) {
        if (navigator.language.indexOf("en") == 0) {
            lang = 'en';
        } else {
            lang = 'zh';
        }
    }

    if ((getUrlKey('lang') != null && getUrlKey('lang').indexOf('en') === 0)) {
        lang = 'en';
    } else {
        lang = 'zh';
    }
    return lang;
}


//生成uuid
export function getUuid(len, radix) {
    const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    let uuid = [], i;
    radix = radix || chars.length;
    if (len) {
        for (i = 0; i < len; i++) {
            uuid[i] = chars[0 | Math.random() * radix];
        }
    } else {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
}

//开始网络遮罩
export function startNetWork(msgText, type = 'normal') {
    if (document.getElementById('rootView').contains(loadDialog)) {
        document.getElementById('rootView').removeChild(loadDialog);
    }


    loadDialog = document.createElement('div');
    loadDialog.className = type !== "normal" ? 'pop-container' : 'load-container';

    let loadImage = document.createElement('img');
    loadImage.className = 'loading_img';
    loadImage.src = '';
    loadDialog.appendChild(loadImage);
    document.getElementById('rootView').appendChild(loadDialog);
}

//结束网络遮罩
function stopNetWork() {
    if (document.getElementById('rootView').contains(loadDialog)) {
        document.getElementById('rootView').removeChild(loadDialog);
    }

}

//设置遮罩
export function setShade(msgText) {
    if (document.getElementById('rootView').contains(loadDialog)) {
        document.getElementById('rootView').removeChild(loadDialog);
    }
    loadDialog = document.createElement('div');
    loadDialog.className = 'load-container';
    loadDialog.innerText = msgText ? msgText : '加载中...';
    document.getElementById('rootView').appendChild(loadDialog);
}


export function changeUrlArg(url, arg, val) {
    let pattern = arg + '=([^&]*)';
    let replaceText = arg + '=' + val;
    return url.match(pattern) ? url.replace(eval('/(' + arg + '=)([^&]*)/gi'), replaceText) : (url.match('[\?]') ? url + '&' + replaceText : url + '?' + replaceText);
}
